<?php

namespace Tools\Root\HttpClient;

/**
 * Class ClientFactory
 *
 * @package Tools\Root\HttpClient
 */
final class ClientFactory
{
    /**
     * Factory Pattern.
     */
    use Factory;

    /**
     * Storage file.
     *
     * @var string
     */
    public static string $fileStorage = './storage';

    /**
     * Service config.
     *
     * @var array
     */
    public static array $serviceConfig = [
        'schema' => 'http',
        'host' => '127.0.0.1',
        'port' => 8000,
    ];

    /**
     * Create client.
     *
     * @param string $class
     * @return Client
     * @throws \Exception
     */
    public static function newClient(string $class) : Client
    {
        /**
         * @var Client $client
         */
        $client = new $class(self::$fileStorage, self::$serviceConfig);
        $client->initialize();

        if (!$client->status()) {
            self::closeClient($client);

            throw new \Exception('Create failure!');
        }

        return $client;
    }

    /**
     * Close client.
     *
     * @param Client $client
     */
    public static function closeClient(Client $client) : void
    {
        $client->close();
    }

    /**
     * Create client.
     *
     * @param string $drive
     * @return Client
     */
    public static function createClient(string $drive) : Client
    {
        $method = "create{$drive}Client";

        return self::{$method}();
    }

    /**
     * HanZi
     *
     * @return Client
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Exception
     */
    public static function createHanZiClient() : Client
    {
        $client = new \Root\Tools\HttpClient\Clients\HanZiClient(self::$fileStorage, self::$serviceConfig);
        $client->initialize();

        if (!$client->status()) {
            $client->close();

            throw new \Exception('Create failure!');
        }

        return $client;
    }
}
